let chatInfo = {
    chatSign: null,
    userName: null, // 确保设置用户名，这里假设是从某个地方获取的
    message: null,
};

// WebSocket URL 和 WebSocket对象
let websocketUrl1 = "ws://" + location.host + "/chat";
let websocket1 = new WebSocket(websocketUrl1);

websocket1.onopen = function() {
    console.log("连接聊天成功!");
}

websocket1.onclose = function() { // 使用正确的事件名 'onclose' 而不是 'close'
    console.log("和聊天服务器断开连接!");
}

websocket1.onerror = function() {
    console.log("和聊天服务器的连接出现异常!");
}

// 接收消息逻辑
websocket1.onmessage = function (result) {
    console.log("[chatMessage] " + result.data);
    let resp = JSON.parse(result.data);
    console.log(resp.chatSign);
    // 判断是否是聊天消息
    if (resp.chatSign != "chat") {
        console.log("因为chatSign退出了！")
        return;
    }

    // 假设 resp.message 是一个数组
    let htmlMes = "";
    for (let mes of resp.message) {
        mes.message = mes.message.replace(/\n/g, '<br>');
        // htmlMes += ("<div>" + mes.userName +  ": </div> <div>" + mes.message +  "</div><br>");
        let messageElement =
            '<div style="min-height: 20px"><div style="padding-left : 20px;width: 40%; min-height: 20px;float: left;font-weight: bold;">' + mes.userName + ':</div>' +
            '<div style="width: 60%; min-height: 20px;float: left;">'+ mes.message +'</div>'
            + '</div><br>';

        htmlMes += messageElement;
    }

    console.log(htmlMes);
    chatDisplay.innerHTML = htmlMes;

}

window.onbeforeunload = function() {
    websocket1.close();
}

let messageInput = document.querySelector("#message-input");
let chatDisplay = document.querySelector("#chat-display");
let sendButton = document.querySelector("#send-message");

// 发送消息逻辑
sendButton.onclick = function () {
    chatInfo.message = messageInput.value;
    chatInfo.chatSign = "chat";
    console.log(chatInfo.chatSign);
    console.log(chatInfo.message);
    console.log(chatInfo.userName);
    websocket1.send(JSON.stringify(chatInfo)); // 使用正确的 WebSocket 对象
    messageInput.value = ''; // 清空输入框
}





